<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\ChatRoom;
use app\common\model\User;
use app\api\common\Program;
use app\api\controller\Push;
use ChuangLanSms;
use fast\Random;
use think\Cache;
use think\Db;

/**
 * 手机短信接口
 */
class Sms extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /**
     * 发送验证码
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $event 事件名称
     * @path api/sms/send
     */
    public function send()
    {
        $mobile = $this->request->post("mobile");
        $event = $this->request->post("event");
        $user_id = $this->request->param("user_id");
        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        if(!$event){
            $this->error(__('事件名称不能为空'));
        }
        if($event == "register"){
            $info = User::where(["tel"=>$mobile,"logout"=>'0'])->find();
            if($info){
                $this->error(__('手机号已存在,请直接登录'));
            }
        }
        if($event == "login"){
            $info = User::where(["tel"=>$mobile,"logout"=>'0'])->find();
            if(!$info){
                $this->error(__('手机号未注册'));
            }
        }
        if($event == "bind"){
            if(!$user_id){
                $this->error("用户Id不能为空");
            }
            $userInfo = User::where(["user_id"=>$user_id,"logout"=>'0'])->find();
            if($userInfo->tel){
                $this->error("已绑定手机号");
            }
//            $info = User::where(["tel"=>$mobile,"logout"=>'0'])->find();
//            if($info){
//                $this->error(__('手机号已存在'));
//            }
        }
        //此处需要调用发送短信
        $code = get_code();
        $this->sendSms($mobile, $code);
        $name = $event.'_'.$mobile;
        Cache::set($name,$code,900);
        $this->success("发送成功",$code);
    }

    public function sendSms($phone, $code)
    {
        //设置编码格式为utf-8;json格式统一使用utf-8封装
        header(
            "Content-type:text/html; charset=UTF-8"
        );
        //实例化 ChuangLanSms 类
        $api  = new ChuangLanSms();
        //生成随机数（6位数）
        $code = "【汽界通商】您的验证码为：".$code."。验证码提供给他人可能导致密码泄露，请勿转发或泄露";
        //设置您要发送的内容：其中“【】”中括号为运营商签名符号，多签名内容前置添加提交
        $result = $api->sendSMS($phone, $code);
        if (!is_null(json_decode($result))) {
            $output=json_decode($result, true);
            if (isset($output['code'])  && $output['code']=='0') {
                return $result;
            } else {
                return $output['errorMsg'];
            }
        } else {
            return $result;
        }
    }

    /**
     * 创建环信用户
     * @ApiMethod (POST)
     * @path api/sms/informationUser
     */
    public function informationUser()
    {
        $identification = Random::alnum(16);
        $user_token = ChatRoom::getUserToken($identification);
        $customer_data = [];
        $customer_data['identification'] = $identification;
        $customer_data['access_token'] = $user_token['data']['access_token'];
        $customer_data['uuid'] = $user_token['data']['user']['uuid'];
        $customer_data['create_time'] = time();
        $res = Db::name("customer")->insert($customer_data);
        if($res){
            $this->success("创建成功");
        }else{
            $this->error("创建失败");
        }
    }

    /*
     * 小程序消息推送
     * @path api/sms/messagePush
     * */
    public function messagePush()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce     = $_GET["nonce"];
        $echostr = $_GET["echostr"];
        $token  = 'mDphvGjucnEZgWXR';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if( $tmpStr  == $signature && $echostr ){
            //第一次接入weixin api接口的时候
            echo  $echostr;
            exit;
        }else{
            echo "error".$tmpStr;
            exit;
        }
    }

    /**
     * @ApiMethod (POST)
     * 极光、环信推送任务
     * @path api/sms/pushTask
     */
    public function pushTask()
    {
        $task_list = Db::name("notice_task")->where("id",">",0)->field("*")->select();
        $push = new Push();
        $num = 0;
        if($task_list){
            foreach ($task_list as &$value){
                // if($value["type"] == 1 && !empty($value["jg_registration_id"])){
                //     $push->androidPush($value["jg_registration_id"],$value["title"]);
                // }
                if($value["type"] == 2 && !empty($value["hx_identification"])){
                    ChatRoom::sendToUser('EWx24UyplePq3vR5',$value['hx_identification'],$value["content"]);
                }
                Db::name("notice_task")->where("id",$value["id"])->delete();
                $num++;
            }
        }
        echo $num;
    }

    /*
     * 获取小程序access_token
     * */
    public function getToken()
    {
        $access_token = Program::getAccessToken();
        dump($access_token);die();
        $content = "/uploads/20240626/1e6b258ece6dd811faf1c7e0f0bbd9a7.jpg";
        $openid = "ovkgW7dTqaZqBMhCfHru14hRkX3I";
        $res = Program::VideoRecognition($content,2,$openid);
        if($res['code'] == 200 && $res['label'] != 100){
            $this->error($res['data']);
        }
        dump($res);die();
    }

}
